package com.task.platform.controller;


import com.task.platform.common.R;
import com.task.platform.exception.CustomException;
import com.task.platform.service.UserService;
import com.task.platform.bo.sys.po.User;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.List;

@Slf4j
@RestController
@RequestMapping("/auth")
public class AuthController {
    @Autowired
    private UserService userService;

    /***
     * 注册
     * @param user
     * @return
     */
    //todo 改接口做成防刷的方式，每个ip限制次数，防止被攻击
    @PostMapping("/register")
    public R<String> register(@RequestBody User user) {
        return R.success(userService.register(user));
    }

    //todo 改接口做成防刷的方式，每个ip限制次数，防止被攻击

    /**
     * 批量注册
     *
     * @param users
     * @return
     */
    @PostMapping("/batchRegister")
    public R<String> batchRegister(@RequestBody List<User> users) {
        userService.batchRegister(users);
        return R.success();
    }

    //todo 改接口做成防刷的方式，每个ip限制次数，防止被攻击
    @PostMapping("/login")
    public R<String> login(@RequestBody User user) {
        return R.success(userService.getJwt(user));
    }

    @PostMapping("/logout")
    public R<String> request(HttpServletRequest request, HttpServletResponse response) {
        try {
            request.logout();
        } catch (ServletException e) {
            log.error("logout error", e);
            throw new CustomException("logout error");
        }
        return R.success();
    }


}
